package com.yhd.admin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yhd.admin.bean.Function;
import com.yhd.admin.mapper.FunctionMapper;
import com.yhd.admin.utils.StringUtils;

@Service
public class FunctionServiceImpl implements FunctionService {
	@Autowired
	private FunctionMapper functionMapper;
	
	//异步 
	@Override
	public List<Function> getAsyncChildrenByPid(Integer pid) {
		return functionMapper.getFunctionsByPid(pid);
	}

	@Override
	public Function checkFunctionName(Function function) {
		List<Function> sons = functionMapper.getFunctionsByPid(function.getPid());
		for(Function f:sons){
			if(function.getName().equals(f.getName())){
				return f;
			}
		}
		return null;
	}

	@Override
	public void addFunction(Function function) {
		functionMapper.add(function);
	}

	@Override
	public Function getFunctionById(int id) {
		return functionMapper.getFunctionById(id);
	}

	@Override
	public void updateFunction(Function function) {
		functionMapper.update(function);
	}

	//递归删除功能
	@Override
	public void deleteFunctionById(int id) {
		List<Function> sons = functionMapper.getFunctionsByPid(id);
		for(Function son : sons){
			deleteFunctionById(son.getId());
		}
		
		functionMapper.delete(id);
	}
	
	//同步加载子功能(包括子功能的子功能，就是递归加载)
	@Override
	public List<Function> getSyncChildrenByPid(Integer pid) {
		//第一级子功能
		List<Function> funcs = functionMapper.getFunctionsByPid(pid);
		for(Function f : funcs){
			//是否是父功能
			if(StringUtils.isEmpty(f.getUrl())){
				//要调用自己
				List<Function> children = getSyncChildrenByPid(f.getId());
				f.setChildren(children);
			}
		}
		return funcs;
	}

}
